package com.mingzhi.forum.interceptor;

import com.mingzhi.forum.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登陆拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    //从配置文件中获取默认登陆页的URL
    @Value("${mingzhi-forum.login.url}")
    private String defaultURL;

    /**
     * 预处理（请求的前置处理） 回调方法
     * @return true 流程继续 <br/> false 流程中断
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户session，并判断用户是否登陆
        HttpSession session = request.getSession(false);
        //进行判断
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null){
            //用户登陆
            return true;
        }
        //没有登录，强制跳转到登陆页面
        if (!defaultURL.startsWith("/")){
            defaultURL = "/" + defaultURL;
        }
        response.sendRedirect(defaultURL);
        return false;
    }
}
